from django_redis import get_redis_connection
from rest_framework import serializers


class ImageCodeCheckSerializer(serializers.Serializer):
    """
    图片,电话号码校验
    """
    image_code_id = serializers.UUIDField()
    text = serializers.CharField(max_length=4, min_length=4)

    # GET / sms_codes / (?P < mobile > 1[3 - 9]\d{9}) / ?image_code_id = xxx & text = xxx
    def validate(self, attrs):
        """
        图片验证码, 电话号码校验
        :param attrs:
        :return:
        """
        # 1 获取参数
        image_code_id = attrs['image_code_id']
        text = attrs['text']

        # 2 从redis中取出验证码的值
        # 连接redis
        redis_conn = get_redis_connection('verify_codes')
        # 取出验证码, 验证码是byte类型
        real_image_code_text = redis_conn.get("img_%s" % image_code_id)

        if not real_image_code_text:
            raise serializers.ValidationError('图片验证码无效')

        # 删除验证码
        redis_conn.delete("img_%s" % image_code_id)

        # 查看验证码和前端传来的值是否一致
        real_image_code_text = real_image_code_text.decode()
        if real_image_code_text.lower() != text.lower():
            raise serializers.ValidationError('图片验证码错误')

        # 2 检查是否在60s内有发送记录

        # get_serializer()中kwargs['context'] = self.get_serializer_context(),
        # get_serializer_context 中提供了 request, format, view
        mobile = self.context['view'].kwargs['mobile']
        send_flag = redis_conn.get('send_flag_%s' % mobile)

        if send_flag:
            raise serializers.ValidationError('请求次数频繁')

        return attrs
